package org.company.mars.zookeeper.monitor;

import java.io.IOException;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class Executor implements Runnable,Watcher{

    private DataMonitor dm;
    
    private DataMonitor.DataMonitorListener listener;
    
    public Executor(String hostPort,String znode,String filename,String exec[]) throws IOException {
        ZooKeeper zk = new ZooKeeper(hostPort, 3000, this);
        listener = new MyStatListener(filename, exec);
        dm = new DataMonitor(zk, znode, listener);
    }
    
    @Override
    public void run() {
        try{
            synchronized (this) {
                while(!dm.dead) {
                    wait();
                }
            }
        }catch(InterruptedException e) {
            
        }
    }
    
    @Override
    public void process(WatchedEvent event) {
        // TODO Auto-generated method stub
        dm.process(event);
    }
    
    public static void main(String[] args) {
        if(args.length < 4) {
            System.err.println("Usage: Executor hostPort znode filename program [args...]");
            System.exit(2);
        }
        
        String hostPort = args[0];
        String znode = args[1];
        String filename = args[2];
        String[] exec = new String[args.length-3];
        System.arraycopy(args, 3, exec, 0, exec.length);
        
        try {
            new Executor(hostPort, znode, filename, exec).run();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
